package com.ihisun.tmhcms.core.service.ossservice.impl;


import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;

import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;

import com.ihisun.tmhcms.core.service.ossservice.BaseService;
import com.ihisun.tmhcms.core.service.ossservice.ResourceUtilService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author wanglai
 * @description: 公共的基础服务
 * @date 2019/1/12 11:59
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class BaseServiceImpl implements BaseService {

    private static final String ABSOLUTE_URL = "http";

    @Value("${webapi_url}")
    private String webapiUrl;

    @Autowired
    private ResourceUtilService resourceUtilService;

    @Override
    public void uploadSingleFile(InputStream inputStream, String fileName) {
        OSSClient ossClient =
                new OSSClient(
                        resourceUtilService.aliyunOssEndpointShanghai(),
                        resourceUtilService.aliyunAccessKey(),
                        resourceUtilService.aliyunAccessSecret());
        try {
            // 创建上传Object的Metadata
            String bucketName = resourceUtilService.aliyunOssInputBucketName();
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public void getOssRealUrl(HttpServletResponse response, String localUrl) {
        // 处理封面图数据
       /* OSSClient ossClient =
                new OSSClient(
                        resourceUtilService.aliyunOssEndpointShanghai(),
                        resourceUtilService.aliyunAccessKey(),
                        resourceUtilService.aliyunAccessSecret());*/
        OSSClient ossClient = getOSSClient();
        String bucketName = resourceUtilService.aliyunOssInputBucketName();
        // 设置URL过期时间为1小时
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, localUrl, expiration);
        log.info("---------------url" + url);
       /* String s = url.toString();
        String[] split = s.split(":");
        String x = split[1];
        String urls = "https:" + x;*/
        try {
            response.sendRedirect(url.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public OSSClient getOSSClient() {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        return new OSSClient(resourceUtilService.aliyunOssEndpointShanghai(), resourceUtilService.aliyunAccessKey(), resourceUtilService.aliyunAccessSecret(), clientConfiguration);
    }


    @Override
    public String getRealResponseUrl(String actionUrl) {
        int absoluteCheckIndex = 4;
        // 对actionUrl的判断
        if (actionUrl == null || actionUrl.isEmpty() || actionUrl.length() <= absoluteCheckIndex) {
            return null;
        }
        if (ABSOLUTE_URL.equals(actionUrl.substring(0, absoluteCheckIndex))) {
            // 绝对地址
            return actionUrl;
        }
        // 相对地址返回
        return webapiUrl + "/common/image/getRealImageUrl?realUrl=" + actionUrl;
    }

    @Override
    public Map<String, String> getOssSignForWeb(String businessCode, String userCode)
            throws Exception {
        // 数据封装访问机制
        String endPoint = resourceUtilService.aliyunOssEndpointShanghai();
        String bucketName = resourceUtilService.aliyunOssInputBucketName();
        String accessKeyId = resourceUtilService.aliyunAccessKey();
        String accessKeySecret = resourceUtilService.aliyunAccessSecret();
        String host = "https://" + bucketName + "." + endPoint;
        // 自定义的文件名称
        Calendar now = Calendar.getInstance();
        String year = now.get(Calendar.YEAR) + "/";
        String month = (now.get(Calendar.MONTH) + 1) + "/";
        String day = now.get(Calendar.DAY_OF_MONTH) + "/";
        String dir = businessCode + "/" + userCode + "/" + year + month + day;
        // 请求数据资源
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            Map<String, String> respMap = new HashMap<>(6);
            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("webapiUrl", webapiUrl + "/common/image/getRealImageUrl?realUrl=");
            return respMap;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    private AssumeRoleResponse assumeRole(
            String accessKeyId,
            String accessKeySecret,
            String roleArn,
            String roleSessionName,
            ProtocolType protocolType,
            long durationSeconds)
            throws ClientException {
        // 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setDurationSeconds(durationSeconds);
        // 发起请求，并得到response
        AssumeRoleResponse response = client.getAcsResponse(request);
        return response;
    }

    @Override
    public void copyOssFile(String sourceObjectName, String destinationObjectName) {
        // 处理封面图数据
        OSSClient ossClient =
                new OSSClient(
                        resourceUtilService.aliyunOssEndpointShanghai(),
                        resourceUtilService.aliyunAccessKey(),
                        resourceUtilService.aliyunAccessSecret());
        try {
            String bucketName = resourceUtilService.aliyunOssInputBucketName();
            CopyObjectResult copyObjectResult =
                    ossClient.copyObject(bucketName, sourceObjectName, bucketName, destinationObjectName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }
}
